package org.example.book.factory;

import org.example.book.strategy.PayStrategyInterface;
import org.example.book.strategy.context.PayContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 具体工厂类
 *
 * @author jeff
 */
@Component
public class PayContextFactory extends AbstractPayContextFactory<PayContext> {

    private static final Map<String, PayContext> payContexts = new ConcurrentHashMap<>();

    @Override
    public PayContext getContext(Integer payType) {
        StrategyEnum strategyEnum =
                payType == 1 ? StrategyEnum.alipay :
                        payType == 2 ? StrategyEnum.wechat :
                                null;
        if (strategyEnum == null) {
            throw new UnsupportedOperationException("paytype not supported");
        }
        PayContext payContext = payContexts.get(strategyEnum.name());
        if (payContext == null) {
            String ref = strategyEnum.getValue();
            try {
                PayStrategyInterface payStrategy = (PayStrategyInterface) Class.forName(ref).newInstance();
                payContext = new PayContext(payStrategy);
                payContexts.put(strategyEnum.name(), payContext);
            } catch (Exception e) {
                throw new UnsupportedOperationException("paytype not supported");
            }
        }
        return payContexts.get(strategyEnum.name());
    }
}
